package com.tim.app.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventListener;
import com.application.library.runtime.event.EventManager;
import com.application.library.util.KeyboardChangeListener;
import com.application.library.widget.EmptyLayout;
import com.application.library.widget.EmptyView;
import com.application.library.widget.loadmore.LoadMoreContainer;
import com.application.library.widget.loadmore.LoadMoreHandler;
import com.application.library.widget.loadmore.LoadMoreRecycleViewContainer;
import com.application.library.widget.recycle.HorizontalDividerItemDecoration;
import com.application.library.widget.recycle.WrapRecyclerView;
import com.application.library.widget.refresh.PtrFrameLayout;
import com.application.library.widget.refresh.PtrHandler;
import com.google.gson.Gson;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.R;
import com.tim.app.callback.ReplyCallback;
import com.tim.app.constant.AppKey;
import com.tim.app.constant.EventTag;
import com.tim.app.server.api.API_Found;
import com.tim.app.server.api.API_Statistics;
import com.tim.app.server.entry.Comment;
import com.tim.app.server.entry.Dynamic;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.net.ServerAddressManager;
import com.tim.app.server.result.CommentResult;
import com.tim.app.server.result.DynamicDetailResult;
import com.tim.app.server.result.PublishCommentResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.share.CustomShareBoard;
import com.tim.app.ui.adapter.comment.CommentInfoAdapter;
import com.tim.app.ui.view.DynamicHeadView;
import com.tim.app.util.SoftKeyboardUtil;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

import java.util.ArrayList;
import java.util.List;


/**
 * 动态详情页面
 */
public class DynamicDetailActivity extends BaseActivity implements PtrHandler, LoadMoreHandler, KeyboardChangeListener.KeyBoardListener {

    public static final String TAG = "DynamicDetailActivity";
    private boolean isFromPush = false;

    private boolean isShow;

    private ImageButton ibBack;
    private TextView tvTitle;
    private ImageButton ibMore;

    EmptyLayout emptyLayout;
    private LoadMoreRecycleViewContainer load_more;
    private WrapRecyclerView wrvComment;
    private DynamicHeadView headView;
    private CommentInfoAdapter adapter;
    private List<Comment> dataList;

    private TextView tvPublish;
    private EditText etComment;

    private Dynamic dynamic;

    private int pageNumber = 1;
    private KeyboardChangeListener mKeyboardChangeListener;

    public static void start(Context context, Dynamic data, boolean isFromPush) {
        Intent intent = new Intent(context, DynamicDetailActivity.class);
        intent.putExtra("data", data);
        intent.putExtra(AppKey.IS_FROM_PUSH, isFromPush);
        if (isFromPush) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }

    public static void startWithShowKeyboard(Context context, Dynamic data, boolean isShow) {
        Intent intent = new Intent(context, DynamicDetailActivity.class);
        intent.putExtra("data", data);
        intent.putExtra("isShow", isShow);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_dynamic_detail;
    }


    @Override
    public void initView() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);

        ibBack = (ImageButton) findViewById(R.id.ibBack);
        tvTitle = (TextView) findViewById(R.id.tvTitle);
        ibMore = (ImageButton) findViewById(R.id.ibMore);

        load_more = (LoadMoreRecycleViewContainer) findViewById(R.id.load_more);
        wrvComment = (WrapRecyclerView) findViewById(R.id.wrvComment);
        headView = (DynamicHeadView) LayoutInflater.from(this).inflate(R.layout.dynamic_head_view, null);

        emptyLayout = new EmptyLayout(this, load_more);
        emptyLayout.setEmptyDrawable(R.drawable.ic_empty_search);
        emptyLayout.setEmptyText("该内容已经被删除了", "");

        wrvComment.setOverScrollMode(View.OVER_SCROLL_NEVER);
        tvPublish = (TextView) findViewById(R.id.tvPublish);
        etComment = (EditText) findViewById(R.id.etComment);

        dynamic = (Dynamic) getIntent().getSerializableExtra("data");
        isFromPush = getIntent().getBooleanExtra(AppKey.IS_FROM_PUSH, false);
        isShow = getIntent().getBooleanExtra("isShow", false);

        if (dataList == null) {
            dataList = new ArrayList<>();
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        wrvComment.setLayoutManager(layoutManager);
        adapter = new CommentInfoAdapter(this, dataList, AppKey.TYPE_DYNAMIC, dynamic.getId());
        load_more.useDefaultFooter(View.GONE);
        load_more.setAutoLoadMore(true);
        load_more.setLoadMoreHandler(this);
        ibBack.setOnClickListener(this);
        ibMore.setOnClickListener(this);

        mKeyboardChangeListener = new KeyboardChangeListener(this);
        mKeyboardChangeListener.setKeyBoardListener(this);
        tvPublish.setOnClickListener(this);
        etComment.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(etComment.getText().toString())) {
                    tvPublish.setEnabled(true);
                } else {
                    tvPublish.setEnabled(false);
                }
            }
        });
        etComment.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    if (!UserManager.ins().isLogin()) {//跳转登录并且抢走焦点
                        wrvComment.setFocusable(true);
                        wrvComment.requestFocus();
                        ViewGT.gotoLoginActivity(DynamicDetailActivity.this);
                    }
                } else {// 此处为失去焦点时的处理内容

                }
            }
        });

        wrvComment.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                SoftKeyboardUtil.hideSoftKeyboard(etComment);
                return false;
            }
        });
        wrvComment.setAdapter(adapter);
        wrvComment.addHeaderView(headView);
        wrvComment.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this).color(getResources().getColor(R.color.transparent)).size((int) getResources().getDimension(R.dimen.dimen_5)).build());


        if (null != dynamic.getUserMsg() && !TextUtils.isEmpty(dynamic.getUserMsg().getUserId())) {
            if (dynamic.getUserMsg().getUserId().equals(UserManager.ins().getUserId())) {
                tvTitle.setText(getString(R.string.myDynamic));
            } else {
                if (!TextUtils.isEmpty(dynamic.getUserMsg().getName())) {
                    tvTitle.setText(getString(R.string.someOneDynamic, dynamic.getUserMsg().getName()));
                }
            }
        }
        headView.setData(dynamic);

        if (isShow) {
            etComment.setFocusable(true);
            etComment.requestFocus();
            SoftKeyboardUtil.showSoftKeyboard(etComment);
        }
        EventManager.ins().registListener(EventTag.ACCOUNT_UPDATE_INFO, eventListener);
        EventManager.ins().registListener(EventTag.DO_REPORT, eventListener);
        EventManager.ins().registListener(EventTag.DO_CONTENT_DELETE, eventListener);
        EventManager.ins().registListener(EventTag.ON_COMMENT_DELETED, eventListener);
        EventManager.ins().registListener(EventTag.ON_SELECT_PEPLY, eventListener);
        EventManager.ins().registListener(EventTag.DO_SHOW_KEYBOARD, eventListener);
        API_Statistics.ins().addDetailData(TAG, this, AppKey.TYPE_DYNAMIC, dynamic.getId());
    }

    @Override
    public void initData() {
        API_Found.ins().getDynamicDetailInfo(TAG, dynamic.getId(), detailCallBack);
        API_Found.ins().getCommentList(TAG, AppKey.NO_SORT, AppKey.TYPE_DYNAMIC, dynamic.getId(), pageNumber, AppKey.PAGE_SIZE, refreshCallback);
    }

    StringResponseCallback detailCallBack = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                DynamicDetailResult result = new Gson().fromJson(resultValue, DynamicDetailResult.class);

                if (null != result && null != result.getRes() && null != result.getRes().getPublish()) {
                    dynamic = result.getRes().getPublish();
                    headView.setData(dynamic);
                }
            } else if (errCode == ResponseResult.ResultStatus.DELETED) {
                emptyLayout.showEmpty();
                EmptyActivity.start(DynamicDetailActivity.this);
                finish();
            } else {
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    StringResponseCallback refreshCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                CommentResult result = new Gson().fromJson(resultValue, CommentResult.class);

                if (null != result && null != result.getRes()) {
                    dataList.clear();
                    if (null != result && null != result.getRes() && null != result.getRes().getArraylist() && null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                    }
                    adapter.notifyDataSetChanged();
                    if (result.getRes().getArraylist().getCurrentPageNo() != result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }

                } else {
                    load_more.loadMoreFinish(false, false);
                }

            } else {
                load_more.loadMoreFinish(false, false);
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    StringResponseCallback moreCallback = new StringResponseCallback() {
        @Override
        public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
            if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                CommentResult result = new Gson().fromJson(resultValue, CommentResult.class);

                if (null != result && null != result.getRes()) {
                    if (null != result && null != result.getRes() && null != result.getRes().getArraylist() && null != result.getRes().getArraylist().getResult()) {
                        dataList.addAll(result.getRes().getArraylist().getResult());
                        pageNumber = result.getRes().getArraylist().getCurrentPageNo();
                    }
                    adapter.notifyDataSetChanged();
                    if (result.getRes().getArraylist().getCurrentPageNo() != result.getRes().getArraylist().getTotalPageCount()) {
                        load_more.loadMoreFinish(false, true);
                    } else {
                        load_more.loadMoreFinish(false, false);
                    }
                } else {
                    load_more.loadMoreFinish(false, false);
                }

            } else {
                load_more.loadMoreFinish(false, false);
                ToastUtil.showToast(errMsg);
            }
            return false;
        }
    };

    EventListener eventListener = new EventListener() {
        @Override
        public void handleMessage(int what, int arg1, int arg2, Object dataobj) {
            switch (what) {
                case EventTag.ACCOUNT_UPDATE_INFO:
                    initData();
                    break;
                case EventTag.DO_REPORT://举报
                    if (UserManager.ins().isLogin()) {
                        UserManager.ins().report(TAG, AppKey.TYPE_DYNAMIC, dynamic.getId());
                    } else {
                        ViewGT.gotoLoginActivity(DynamicDetailActivity.this);
                    }
                    break;
                case EventTag.DO_CONTENT_DELETE://删除
                    deleteMyDynamic();
                    break;
                case EventTag.ON_COMMENT_DELETED://被删除
                    int position = (int) dataobj;
                    if (dataList.size() > position) {
                        dataList.remove(position);
                        adapter.notifyDataSetChanged();
                        dynamic.setCommentCount(dynamic.getCommentCount() - 1);
                        headView.updateDyanmicCommentCount(dynamic);
                    }
                    break;
                case EventTag.ON_SELECT_PEPLY://选中评论
                    String typeId = String.valueOf(arg1);
                    Comment selectComment = (Comment) dataobj;
                    if (typeId.equals(dynamic.getId())) {
                        etComment.setHint(getString(R.string.replySomeone, selectComment.getUserMsg().getName()));
                        isReply = true;
                    }
                    etComment.setFocusable(true);
                    etComment.requestFocus();
                    SoftKeyboardUtil.showSoftKeyboard(etComment);
                    break;
                case EventTag.DO_SHOW_KEYBOARD:
                    etComment.setFocusable(true);
                    etComment.requestFocus();
                    SoftKeyboardUtil.showSoftKeyboard(etComment);
                    break;
            }

        }
    };

    boolean isReply = false;

    @Override
    public void onKeyboardChange(boolean isShow, int keyboardHeight) {
        if (!isShow) {
            if (isReply) {
                isReply = false;
                adapter.setReplyComment(null, -1);
                etComment.setText("");
                etComment.setHint(getString(R.string.commentPrompt));
            }
        }
    }

    /**
     * 删除我的故事
     */
    private void deleteMyDynamic() {
        API_Found.ins().deleteMyPublish(TAG, dynamic.getId(), AppKey.TYPE_DYNAMIC, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                if (errCode == ResponseResult.ResultStatus.OK) {
                    ToastUtil.showToast("删除成功");
                    EventManager.ins().sendEvent(EventTag.ON_DYNAMIC_DELETED, 0, 0, dynamic.getId());
                    finish();
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        EventManager.ins().removeListener(EventTag.ACCOUNT_UPDATE_INFO, eventListener);
        EventManager.ins().removeListener(EventTag.DO_REPORT, eventListener);
        EventManager.ins().removeListener(EventTag.DO_CONTENT_DELETE, eventListener);
        EventManager.ins().removeListener(EventTag.ON_COMMENT_DELETED, eventListener);
        EventManager.ins().removeListener(EventTag.ON_SELECT_PEPLY, eventListener);
        EventManager.ins().removeListener(EventTag.DO_SHOW_KEYBOARD, eventListener);
        OkHttpUtils.getInstance().cancelTag(TAG);
        OkHttpUtils.getInstance().cancelTag(CommentInfoAdapter.TAG);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibBack:
                onBackPressed();
                break;
            case R.id.tvPublish:
                String content = etComment.getText().toString();
                if (isReply) {
                    adapter.postReplyComment(content, new ReplyCallback() {
                        @Override
                        public void onSuccess() {
                            dynamic.setCommentCount(dynamic.getCommentCount() + 1);
                            headView.updateDyanmicCommentCount(dynamic);
                            etComment.setText("");
                            etComment.setHint(getString(R.string.commentPrompt));
                            SoftKeyboardUtil.hideSoftKeyboard(etComment);
                        }

                        @Override
                        public void onFail() {
                            ToastUtil.showToast("发布失败，请稍后再试");
                        }
                    });
                } else {
                    publishDynamicComment(content);
                }
                break;
            case R.id.ibMore:
                SoftKeyboardUtil.hideSoftKeyboard(etComment);
                CustomShareBoard shareBoard = new CustomShareBoard(this, CustomShareBoard.ShareFrom.DYNAMIC);
                String targetUrl = "";
                String sinaDesc = "";
                String imageUrl = ServerAddressManager.SHARE_DEFAULT_LOGO_URL;
                if (UserManager.ins().isLogin()) {
                    if (dynamic.getUserMsg().getUserId().equals(UserManager.ins().getUserId())) {
                        shareBoard.setDelete(true);
                    }
                }
                if (null != dynamic.getImageUrl() && dynamic.getImageUrl().size() > 0) {
                    imageUrl = dynamic.getImageUrl().get(0);
                }
                String desc = "";
                if (!TextUtils.isEmpty(dynamic.getTitle())) {
                    desc = dynamic.getTitle();
                } else {
//                    desc = RT.getString(R.string.share_desc_info);
                }
                shareBoard.setShareInfo(dynamic.getTitle(), desc, sinaDesc, imageUrl, imageUrl, targetUrl);
                shareBoard.showPopup(false);
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
        }
        return false;
    }

    @Override
    public void onBackPressed() {
        SoftKeyboardUtil.hideSoftKeyboard(etComment);
        if (isFromPush) {
            ViewGT.gotoMainActivity(DynamicDetailActivity.this);
        } else {
            super.onBackPressed();
        }
    }

    /**
     * 发布评论
     *
     * @param commentContent
     */
    private void publishDynamicComment(String commentContent) {
        API_Found.ins().publishComment(TAG, UserManager.ins().getUserId(), AppKey.TYPE_DYNAMIC, dynamic.getId(), commentContent, new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                SoftKeyboardUtil.hideSoftKeyboard(etComment);
                tvPublish.setEnabled(true);
                if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                    API_Statistics.ins().addActionData(TAG, DynamicDetailActivity.this, AppKey.TYPE_COMMENT);
                    PublishCommentResult result = new Gson().fromJson(resultValue, PublishCommentResult.class);
                    etComment.setText("");
                    Comment comment = result.getRes().getComment();
                    comment.setUserMsg(UserManager.ins().getLoginUser());
                    dataList.add(0, comment);
                    dynamic.setCommentCount(dynamic.getCommentCount() + 1);
                    adapter.notifyDataSetChanged();
                    ToastUtil.showToast("发表成功！");
                } else if (ResponseResult.ResultStatus.BE_ADD_BLACK == errCode) {
                    ToastUtil.showToast("由于对方的设置，你不能评论此说说");
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }


    @Override
    public void onLoadMore(LoadMoreContainer loadMoreContainer) {
        API_Found.ins().getCommentList(TAG, AppKey.NO_SORT, AppKey.TYPE_DYNAMIC, dynamic.getId(), pageNumber + 1, AppKey.PAGE_SIZE, moreCallback);
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return false;
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {

    }

}
